package Tree;

import java.util.ArrayList;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Tree
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-26  08:34
 * @Description: TODO
 * @Version: 1.0
 */
public class 有序链表转化二叉搜索树109 {

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) {
            return null;
        }
        ArrayList<Integer> list = new ArrayList<>();
        ListNode pre = head;
        int index = 0;
        while (pre != null) {
            list.add(pre.val);
            pre = pre.next;
        }
        // result表示就是一个有序数组
        TreeNode root = BuildTree(list.stream().mapToInt(Integer::intValue).toArray(), 0, list.size() - 1);
        return root;
    }

    private TreeNode BuildTree(int[] result, int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = left + (right - left) / 2;
        TreeNode root = new TreeNode(result[mid]);
        root.left = BuildTree(result, left, mid - 1);
        root.right = BuildTree(result, mid + 1, right);
        return root;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
